<?php
 

namespace App\Http\Controllers\Web\Member\Seller;

use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;
use Exception;
use tech\core\Util;
use tech\core\eSign;


include(app_path() ."/Library/API/eSignOpenAPI.php");

class OrderContractController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'eqbao'],
        'show' => ['get', 'eqbao/%d'],
        'store' => ['post', 'eqbao'],
        'update' => ['put', 'eqbao/%d'],
        'find_by_userid'=>['get','eqbao/find_by_userid'],
        
        'contract_index' => ['get', 'seller/order_contract'],
        'contract_show' => ['get', 'seller/order_contract/%d'],
        'contract_store' => ['post', 'seller/order_contract'],
        'contract_update' => ['put', 'seller/order_contract/%d'],
        'find_by_orderid'=>['get','seller/order_contract/find_by_orderid/%d'],
        
        'company_info'=>['get','seller/companymaterial/%d/showusercompany'],
        
        'order_show'  => ['get',  'seller/service/orders/%d'],
        
        'contract_mb_index' => ['get', 'seller/contracts'],
        
        'sendmessage' => ['get', 'sendmessage'], 
        
        'verifycode' => ['get', 'verifycode'],
        
        'qual_update' => ['post', 'seller/attribute/%d'],
        
    ];
    

    protected $request;
    
    protected $sign;
    
    public function __construct(Request $request)
    {
        $this->request = $request;
        
        //实例化
        try {
            $this->sign = new eSign();
        } catch (Exception $e) {
            echo $e->getMessage();
            exit;
        }
    }
    
    
    public function index(){
        
        $search_params = $this->request->all(['order_code', 'created_at','status','keyword']);
        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'page' => $page,
            'with' => 'orderProducts;shop',
            'orderBy'=>'id',
            'sortedBy'=>'desc',
        ];
        
        //请求部分
        $ret = http_web($this->api_url['contract_index'])->send($params);
        
        //结果处理部分
        $data = paginate($this->request, $ret['data']);
    
        //回填搜索框值
        $data['search_params'] = $search_params;
        
        return view('web.user.seller.contract_orders',$data);
    }
    
    /**
     * 初始化和登录
     */
    
    public function init()
    {
        $iRet = $this->sign->init();
        if (0 === $iRet) {
            $array = array(
                "errCode" => 0,
                "msg" => "初始化成功",
                "errShow" => true
            );
            $this->response($array);
        }
    }
    
  
    
    //合同授权
    public function contract_auth(){
        $result = http_web($this->api_url['find_by_userid'])->send();
        $data = [];
        if(isset($result['data'][0])){
            return redirect()->route('web.seller.order_contract.index');
        }
        
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        $data['company_name']  = "";
        $data['company_address']  = "";
        
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['company_name'] = $company['company_name'];
            $data['company_address'] = $company['company_address'];
        }
        
        
        $data['mobile']=session('user_phone');
        
        return view('web.user.seller.contract_admittance',$data);
    }
    
    public function sendsms(){
        $params = $this->request->all(['phone']);
         //发送短信验证
         $data_send = http_web($this->api_url['sendmessage'])->send($params);
         return response()->json($data_send);
    }
 
    public function contract_auth_post()
    {
        $resp = ['status'=>0,'msg'=>""];
        //$this->sign->init();
        $params = $this->request->all(['phone', 'name', 'organCode', 'regType', 'email', 'organType', 'legalArea', 'userType',
            'agentName', 'agentIdNo', 'legalName', 'legalIdNo','auth_card','company_address','code']);
        $params['regType'] = isset($params['regType']) ? $params['regType'] : 1;
        $verify_data = http_web($this->api_url['verifycode'])->send($params);
        if(isset($verify_data['code']) && $verify_data['code']==1){
            $resp['msg'] = $verify_data['message'];
            return response()->json($resp);
        }
       
        
        $ret = $this->sign->addOrganizeAccount(
            $params['phone'],
            $params['name'],
            $params['organCode'],
            $params['regType'] ,
            $params['email'],
            0,//$params['organType'],
            0,//$params['legalArea'] ,
            $params['userType'] ,
            $params['agentName'] ,
            $params['agentIdNo'] ,
            $params['agentName'],//$params['legalName'],对的相同赋值参数
            $params['agentIdNo'] ,//$params['legalIdNo'],对的相同赋值参数
            $address = '',
            $scope = '');
        

        if(isset($ret['accountId'])){
            $data['account_id'] = $ret['accountId'];
            $data['organ_code'] = $params['organCode'];
            $data['user_type'] = $params['userType'];
            $data['auth_name'] = $params['agentName'];
            $data['user_name'] = session("user_name");
            $data['auth_card'] = $params['agentIdNo'];
            $data['company_address'] = $params['company_address'];
            $data['company_name'] = $params['name'];
            
            $ret = $this->sign->addTemplateSeal(
                $ret['accountId'],
                'star',
                'red',
                '合同专用章',
                ''
                );
            if(isset($ret['imageBase64'])){
                $data['yz_data'] = $ret['imageBase64'];
            }
            
            $info = http_web($this->api_url['store'])->send($data);
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['msg'] = $ret['msg'];
            }
        }
        
        return response()->json($resp);
    }
    
    public function contract_msg(){
        $resp = ['status'=>0,'msg'=>"",'code'=>0];
        $order_id = $this->request->get("order_id",0);
        $qid = $this->request->get('qid',0);
        if(!$order_id){
            $resp['msg'] =  '订单号错误';
            return response()->json($resp);
        }
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        if(!isset($result['data'][0])){
            $resp['msg'] =  '请先授权合同';
            $resp['code'] = 1;
            return response()->json($resp);
        }
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        
        if(isset($result['data'][0]['seller_sign_id'])){
            return redirect()->route('web.seller.order_contract.contract_cost',['order_id'=>$order_id]);
        }
        $data = [];
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['company'] = $company;
        }
        $data['order_id']=$order_id;
        $data['qid']=$qid;
        return view('web.user.seller.contract_msg',$data);
    }
    
    public function contract_write(){
        $resp = ['status'=>0,'msg'=>""];
        $order_id = $this->request->get("order_id",0);
        $qid = $this->request->get('qid',0);
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        if(isset($result['data'][0]['seller_sign_id'])){
            return redirect()->route('web.seller.order_contract.contract_cost',['order_id'=>$order_id]);
        }
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        if(!isset($result['data'][0])){
            $resp['msg'] =  '请先授权合同';
            return response()->json($resp);
        }
        
        $base_info['name']=$this->request->get("name","");
        $base_info['phone']=$this->request->get("phone","");
        $base_info['term']=$this->request->get("term","");
        $base_info['bond']=$this->request->get("bond","");
        
        $base_info = json_encode($base_info);
        
        $data = [];
        $params = [
            'orderBy' => 'updated_at',
            'sortedBy' => 'desc',
            'page'=>$this->request->get('page',1)
        ];
        $ret  = http_web($this->api_url['contract_mb_index'])->send($params);
        if(isset($ret['data']['list'])){
            $data['contracts'] = $ret['data']['list'];
        }
        
        
        $ret = http_web($this->api_url['order_show'], [$order_id])->send($params);
        $data['buyer_user_id'] = 0;
        $order_code = "";
        if(isset($ret['data']['user_id']) && $ret['data']['user_id']){
            $order_code = $ret['data']['order_code'];
            $data['buyer_user_id'] = $ret['data']['user_id'];
            $info = http_web($this->api_url['company_info'],[$ret['data']['user_id']])->send();
            if(isset($info['data']['data']['company'])){
                $company = $info['data']['data']['company'];
                $data['buyer_company'] = $company;
            }
        }
        
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        
        if(isset($info['data']['data']['company'])){
            $company = $info['data']['data']['company'];
            $data['seller_company'] = $company;
        }
        
        $data['contract_code'] = 'HT'.substr($order_code,5).rand(10,100);
        $data['base_info']=$base_info;
        $data['order_id']=$order_id;
        $data['qid']=$qid;
        
        return view('web.user.seller.contract_write',$data);
    }
    
    public function contract_post(){
        $data['order_id'] = $this->request->post('order_id','');
        $qid = $this->request->get('qid',0);
        $data['seller_user_id'] = session('user_id');
        $data['seller_sign_id'] = 'd';
        $data['status'] = 0;
        $data['contract_content'] = $this->request->post('content','');
        $data['base_info'] = $this->request->post('base_info','');
        $data['contract_code'] = $this->request->post('contract_code','');
        $data['buyer_name']=$this->request->post('buyer_name','');
        $data['seller_name']=$this->request->post('seller_name','');
        $data['buyer_user_id']=$this->request->post('buyer_user_id','');
        $order_id=$data['order_id'];
        $user_type =1;//1seller 2 buyer
        $id = 0;
        
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        if(isset($result['data'][0]['id'])){
            $resp['msg'] = '卖家已签署合同';
            return response()->json($resp);
        } 
        
        $file_url = public_path("uploads").DIRECTORY_SEPARATOR.  $data['contract_code'].'.pdf';
        //
        $pdf = new \TCPDF();
        $pdf->SetCreator('资质合同');
        $pdf->SetAuthor('e#在线');
        $pdf->SetTitle('资质合同');
        $pdf->SetSubject('资质合同');
        $pdf->SetKeywords('TCPDF, PDF, PHP');
        $pdf->setPrintHeader(false);
        $pdf->setFooterData([0, 64, 0], [0, 64, 128]);
        $pdf->setFooterFont(['helvetica', '', '8']);
        $pdf->SetDefaultMonospacedFont('courier');
        $pdf->SetMargins(15, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(10);//页脚bottom间隔
        $pdf->SetAutoPageBreak(true, 25);
        $pdf->setFontSubsetting(true);
        $pdf->SetFont('stsongstdlight', '', 10);
        
        //$pdf->SetFontSize(6);
        $pdf->AddPage();
        $pdf->writeHTML('<body style="width:100%;">');
        $pdf->writeHTML('<p>合同编号：'.$data['contract_code'].'</p>');
        $pdf->Ln(2);
        $pdf->writeHTML('<p >甲方：'.$data['buyer_name'].'</p>');
        $pdf->Ln(2);
        $pdf->writeHTML('<p >乙方：'.$data['seller_name'].'</p>');
        $pdf->Ln(2);
        $pdf->writeHTML('<p >根据《中华人民共和国合同法》及相关法律法规的规定，甲乙双方在平等、自愿、公平、协商一致的基础上，就甲方委托乙方提供服务的有关事宜达成如下协议：</p>');
        $pdf->Ln(2);
        $pdf->writeHTML('<p >合同条例：</p>');
        $pdf->Ln(2);
        
        $pdf->writeHTML('<p>'.$data['contract_content'].'</p>');
        $pdf->Ln(10);
        $pdf->writeHTML('<p><table style="width: 100%;">
            <tr>
                <td >甲方：'.$data['buyer_name'].'</td>
                <td style="text-align: right;">乙方：'.$data['seller_name'].'</td>
            </tr>
            <tr>
                <td >甲方盖章</td>
                <td style="text-align: right;">乙方盖章</td>
            </tr>
        </table></p>');
        $pdf->writeHTML('</body>');
        $pdf->Output($file_url, 'F');//I输出、D下载
        
        $data['file_url']= $file_url;
        $data['web_url'] = asset('uploads/'.$data['contract_code'].'.pdf');
        
       
        $resp = ['status'=>0,'msg'=>""];
        
        $result = http_web($this->api_url['find_by_userid'])->send();
        
        $accountId = "";
        $sealData = "";
        if(isset($result['data']['0']['account_id'])){
            $accountId = $result['data'][0]['account_id'];
            $sealData = $result['data'][0]['yz_data'];
            
            if(!$sealData){
                $resp['msg'] = "请先创建印章";
                return response()->json($resp);
            }
        }else{
            $resp['msg'] = "请先授权合同";
            return response()->json($resp);
        }
        
        if(!$file_url){
            $resp['msg'] = '待签署文件不能为空';
            return response()->json($resp);
        }
        
        $srcPdfFile=$file_url;
        
        $filename = pathinfo($srcPdfFile,PATHINFO_FILENAME);
        $dist_filename = "";
        if($filename){
            $dist_filename = 'uploads/'.$filename.'_dist.pdf';
            $dstPdfFile=public_path($dist_filename);
        }
        
        $signType ='Key';// 'Single';
        $isQrcodeSign = $this->request->post('isQrcodeSign','');
        $signPos = array(
            'posPage' =>  -1,//$this->request->post('posPage',1),
            'posX' =>  0,//500,
            'posY' =>  -30,//100,
            'key' =>   '乙方盖章',
            'width' => 0,
            'isQrcodeSign'  =>  false,
            'addSignTime'=>true,
        );
        $signFile = array(
            'srcPdfFile' => $srcPdfFile,
            'dstPdfFile' => $dstPdfFile,
            'fileName' =>  '',
            'ownerPassword' => ''
        );
        
        $ret = $this->sign->userSignPDF($accountId, $signFile, $signPos, $signType, $sealData, $stream = true);
        
        if(isset($ret['signServiceId'])){
            $data['file_url'] = $dist_filename;
            $data['web_url'] = asset($dist_filename);
            
            $data['order_id'] = $order_id;
            $data['seller_user_id'] = session('user_id');
            $data['seller_sign_id'] = $ret['signServiceId'];
            $data['status'] = 0;
            $info = http_web($this->api_url['contract_store'])->send($data);
            
            if(isset($info['code']) && $info['code'] == 0){
                $resp['status'] = 1;
                $resp['order_id'] = $order_id;
                $resp['msg'] = $ret['msg'];
                $data['q_status'] = '2';
                $ret = http_web($this->api_url['qual_update'], [$qid])->send($data);
                
            }
        }else{
            $resp['msg'] = $ret['msg'];
        }
        
        return response()->json($resp);
        //return redirect()->route('web.seller.order_contract.contract_cost',['order_id'=>$order_id]);
    }
    
    public function contract_cost(){
        $order_id = $this->request->get('order_id','');
        $data = [];
        
        $result = http_web($this->api_url['find_by_orderid'],[$order_id])->send();
        if(!isset($result['data'][0]['seller_sign_id'])){
            $resp['msg'] = '还未签合同';
            return response()->json($resp);
        }
        
        
        $ret = http_web($this->api_url['order_show'], [$order_id])->send();
        
        if(isset($ret['data']['user_id']) && $ret['data']['user_id']){
            $data['order_code'] = $ret['data']['order_code'];
            $info = http_web($this->api_url['company_info'],[$ret['data']['user_id']])->send();
            if(isset($info['data']['data'])){
                $data['buyer_user_name'] = $info['data']['data']['name'];
                $data['buyer_user_phone'] = $info['data']['data']['phone'];
                $data['buyer_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
                $data['buyer_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
                $data['buyer_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
            }
        }
        
        $info = http_web($this->api_url['company_info'],[session('user_id')])->send();
        
        if(isset($info['data']['data'])){
            $data['seller_user_name'] = $info['data']['data']['name'];
            $data['seller_user_phone'] = $info['data']['data']['phone'];
            $data['seller_user_angent'] = isset($info['data']['data']['company']['angent']) ?$info['data']['data']['company']['angent']:"" ;
            $data['seller_company_address'] = isset($info['data']['data']['company']['company_address']) ?$info['data']['data']['company']['company_address']:"" ;
            $data['seller_company_name'] = isset($info['data']['data']['company']['company_name']) ?$info['data']['data']['company']['company_name']:"" ;
        }
        
        old_set($data);
        
        return view('web.user.seller.contract_cost',$data);
    }
    
 
  
    
    private function response($data){
        echo Util::jsonEncode($data);
        exit();
    }
  
   
}